// detail.js
let app = getApp();
import util from '../../../utils/util.js';
var logincontent = '尚未登录，请先登录吗？';
import httpUtil, { KEYS} from '../../../utils/http.js'

/**
 * 需要用到async/await的页面必须加此引入
 */
import regeneratorRuntime from '../../../utils/regenerator-runtime/runtime.js'

const { $Toast } = require('../../../dist/base/index');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    showView:false,
    id: 0,
    info:'',
    pics:{},
    stars: [0, 1, 2, 3, 4],
    normalSrc: '../../../images/starnormal.png',
    selectedSrc: '../../../images/starselected.png',
    halfSrc: '../../../images/starhalf.png',
    key: 2,//评分
    key2:3,
    commentlist:'',
    piclist:'',
    favstatus:0,
    loadingHidden:true,
    isHasActivity: false,
    activity: {},
    shoppf:0,
    scene:{}
  },

  /**
   * 通过二维码扫描进来后，会带进来门店id或手机号，然后显示门店具体信息；否则跳到tab2，即门店列表
   */
  onLoad:async  function (options) {

    const {state,value} = await httpUtil.getObjectFromStorgeAsync(KEYS.SHOP)
    let _data
    if(state){
      _data = value
    }else{
      if (Object.keys(options).length === 0) {
        $Toast({
          content: '暂无门店信息\n,将跳至门店列表页面..',
          type: 'loading'
        });
        setTimeout(() => {
          $Toast.hide();
          wx.navigateTo({
            url: '../../carstore/list/list',
          })
        }, 2000)
        return
      }
      _data = await this.getShopDetail(options.scene)
      httpUtil.setObjectToStorgeAsync(httpUtil.KEYS.SHOP, _data.data.ret)
    }

    this.addScanLoginHistory(options.scene)
    this.reloadHome()
  },
  
  reloadHome:async function(){

    const shop = await httpUtil.getObjectFromStorgeAsync(httpUtil.KEYS.SHOP)
    
    if(!shop.state){
      return
    }
    const _shop = shop.value.data
    const _data = await this.getShopDetail(_shop._id)
    const data = _data.data.ret
    httpUtil.setObjectToStorgeAsync(httpUtil.KEYS.SHOP, data )
    this.refreshNavigatior(data)
    let strary = data.pics.split(",");
    let strarytmp = [];
    for (var index in strary) {
      var str = strary[index];
      if (str != '') {
        var obj = {};
        str = app.globalData.SERVER + 'file/pic/' + str + '.png';
        obj.id = index;
        obj.url = str;
        strarytmp.push(obj);
      }
    }

    var showtype = false;
    if (!data.shopservice && data.shopservice.length > 0) {
      showtype = true;
    }

    var sAttitudeScore = (data.serviceAttitudeScore / data.commentnum).toFixed(0);
    var sSpeedScore = (data.serviceSpeedScore / data.commentnum).toFixed(0);
    this.setData({
      info: data,
      showView: showtype,
      pics: strarytmp,
      key: sAttitudeScore,
      key2: sSpeedScore,
      shoppf: (parseInt(data.serviceScore) / parseInt(data.commentnum)).toFixed(1)
    });


    this.getlist();
    this.isFav();
    this.getActivity();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 页面渲染完成
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   this.reloadHome()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 页面隐藏

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 页面关闭
  },

/**
 * 分享按钮回调
 */
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: this.data.info.shopname,
      path: '/pages/carstore/detail/detail',//实验发现，此处的路径应该写全，写到具体的wxml页面。如path:'/page/user/user?id=123'
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  callphone:function(){
    var that = this;
     wx.makePhoneCall({
       phoneNumber: that.data.info.tel,
     
     })
  },
  showMap:function(){
    var that = this;
    if(this.data.info.location.length==2)
    {

      var lat = this.data.info.location[1];
      var lon = this.data.info.location[0];

      wx.openLocation({
        latitude: lat,
        longitude: lon,
        scale: 18,
        name: that.data.info.shopname,
        address: that.data.info.address,
      })
    }else{
      util.showToast('数据不全暂时无法定位');
    }

    

  },
  getlist() {
    var url = app.globalData.SERVER +'comment/getOneShopAllRepairComments';

    var showinfo = [];
    var shopid = this.data.info._id
    util.request(url, 'POST', {

      page: '0',
      pagesize: '100',
      shopid: shopid,
    }).then(res => {
      util.showToast('成功', 'error', 2500);
    }).catch(err => {
      if (err.data.code === 1) {
        console.log(err.data.ret);

        let strarytmp = [];
        var list = err.data.ret;
        for (var i in list) {
          var listinfo = list[i];
          var pics = listinfo.pics;
        if (pics.length>0)
        {
          var piclist = pics.split(',');
          strarytmp=[];
        for (var info in piclist) {
          var str = piclist[info];
          if (str != '') {
            var obj = {};
            str = app.globalData.SERVER + 'file/pic/' + str + '.png';
            obj.id = info;
            obj.url = str;
            strarytmp.push(obj);
          }
        }
          listinfo.piclist = strarytmp;
          showinfo.push(listinfo);
        }else{
          showinfo.push(listinfo);
        }
        }
        this.setData({
          commentlist: showinfo,
          // piclist:strarytmp,
        });
        var num = 1;
      } else {
      
      }


    });
  },
  setfav: function () {
    this.setData({
      loadingHidden: false
    });
    var usetinfo = util.getData("userinfo");
    if (usetinfo == '') {
      var that = this;
      wx.showModal({
        title: '提醒',
        content: logincontent,
        success: function (eci) {
          if (eci.confirm) {
            wx.navigateTo({
              url: '../../auth/login/login'
            })
          } else {
          }
        }
      });
  
    }else{
      var that = this;
    var url = app.globalData.SERVER + 'fav/add';

      if (this.data.favstatus ==1)
      {
        url = app.globalData.SERVER + 'fav/del';
      }
      var shopid = this.data.info._id
    util.request(url, 'POST', {
      carerid: usetinfo._id,
      shopid: shopid,
    }).then(res => {
      that.setData({
        loadingHidden: true,
      });



      util.showToast('成功', 'error', 2500);
    }).catch(err => {
      that.setData({
        loadingHidden: true,
      });
      if (err.data.code === 1) {
        var ret = 0;
        if (that.data.favstatus == 0)
        {
            ret = 1;
        }else{
            ret = 0;
        }
        that.setData({
          favstatus: ret,
          // piclist:strarytmp,
        });

      } else {
      }
    });
    }
    },

    isFav :function(){
      var usetinfo = util.getData("userinfo");
      var that = this;
      if (usetinfo == '') 
      {
        return;
      }
      var shopid = this.data.info._id
      var url = app.globalData.SERVER + 'fav/isFav';
      util.request(url, 'POST', {
        carerid: usetinfo._id,
        shopid: shopid,
      }).then(res => {
        util.showToast('成功', 'error', 2500);
      }).catch(err => {
        if (err.data.code === 1) {
          
          that.setData({
            favstatus: err.data.ret,
            // piclist:strarytmp,
          });
        
        } else {

        }


      });

    },
    /**
     * 获取最新活动
     */
    getActivity: function () {
      var that = this;
      var url = app.globalData.SERVER + 'activity/getTheLastActivity';
      util.request2(url, 'POST', {
        owner: that.data.info.tel,
      }).then(res => {
        if (res.ret.length > 0) {
          that.setData({
            activity: res.ret[0],
            isHasActivity: true
          });
        } else {
          that.setData({
            activity: {},
            isHasActivity: false
          });
        }
      }).catch(err => {
        
      });
    },

    /**
    * 查看活动详情
    */
    checkActivity:function(){

      // '../../util/webview/webview?url=https://www.autorepairehelper.cn/noticeboard/xcxsysc'
    wx.navigateTo({
      url: '../../util/webview2/webview2?id=' + 
      this.data.activity._id + '&advtip=' + 
        this.data.info.advtip + '&shopname=' + this.data.info.shopname
      })
    },
  showdetail:function (obj) {
    var objkey = parseInt(obj.currentTarget.id);
    var ret = this.data.commentlist[objkey];
    var that = this;
    // var ret = this.data.info;
    let data = JSON.stringify(ret);
    wx.navigateTo({
      url: '../commentdetail/commentdetail?data=' + data,
    });
  },
  addschedule:function(){
    // var usetinfo = wx.getStorageSync("user_info");
    var usetinfo = util.getData("userinfo");
    if (usetinfo == '') 
    {
      var that = this;
      wx.showModal({
        title: '提醒',
        content: logincontent,
        success: function (eci) {
          if (eci.confirm) {
            wx.navigateTo({
              url: '../../auth/login/login'
            })
          } else {
          }
        }
      });
      // return;
    }else{

    
    var that = this;
    
    var ret = this.data.info;
    let data = JSON.stringify(ret);
    wx.navigateTo({
      url: '../../schedule/newschedule/newschedule?data=' + data,
    });
    }
  },

/**
 * 获取门店详情
 */
   async getShopDetail(id){

     $Toast({
       content: 'loading data...',
       type: 'loading'
     });
      const { state, value } = await httpUtil.post('users/getShopInfo', {id:id})
     $Toast.hide();
     if(state){
        return value
     }else{
       return null
     }
  },

  async addScanLoginHistory(id){
    const { state, value } = await httpUtil.post('xcx/addXcxScanLoginHistory', { shopid: id })
  },


  refreshNavigatior(shop){
    wx.setNavigationBarTitle({
      title: shop.shopname
    });
  },

  //end
}
);